package com.jv.test1;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 自定义 Realm
 *
 * 为什么要自定义Realm？
 * shiro 的底层封装了固定的数据库表的名称和字段的名称，这样就造成了使用起来非常不方便
 *
 */
public class UserRealmA extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        try {
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shiro", "root", "root");

            PreparedStatement prepareStatement = conn.prepareStatement("select uname, pwd from  admin ");


            ResultSet rs = prepareStatement.executeQuery();

            while (rs.next()){

                SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(rs.getString("uname"),rs.getString("pwd"),"userRealm");

                return  info;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
